在 react hooks 前,先了解一下所謂的 pure function 跟 side-effect(副作用)
(該不會真的最後30天都是在寫 javascript 而沒寫什麼 react 吧XDD
給我來點純函式(?
當每次傳入相同引數後,都會回傳相同的值的函式即為 pure function
舉例如下
function whatToBuy(itemName){
return (`I should buy some ${itemName}.`);
}
當每次對 whatToBuy 傳入 'juice' 時,每次回傳的值都是 'I should buy some juice.',因此 whatToBuy 就是 pure function
pure function 有幾種特質
另外有點要格外注意,當在 pure function 中呼叫另個 pure function 該 function 仍是 pure function
反之,當函式依賴函式外宣告的變數、每次回傳不同值的函式、函式會造成外部的變數值改變,則該函式則為 impure function
舉例來說...
let dayOfWeek = 'Monday';
let food = 'noodles';
function consumeFood(day , food){
dayOfWeek = 'Wednesday';
return (`I would get some ${food} on ${day}`);
}
console.log(consumeFood( dayOfWeek , food ));
// 'I would get some noodles on Wednesday'
// dayOfWeek 的值被改變為 Wednesday 即為 side-effect
又或是...
let initVal = 0;
function plusRandomVal(val){
return (initVal += Math.floor(Math.random()*10))
}
plusRandomVal(initVal); // 既不知道每次執行後回傳值為多少,且 initVal(在function外的變數)值也會改變
impure function 有幾種特質
幾種常見的 impure function 類型
來看看陣列的幾種方法,並分辨出誰是 pure function / impure function
Array.pop()
Array.push()
Array.map()
Array.filter()
Array.join()
Array.reduce()
Array.slice()
Array.splice()
Array.sort()
Array.reverse()
Ans:
Array.pop() ❌ impure function
Array.push() ❌ impure function
Array.map() ⭕ pure function
Array.filter() ⭕ pure function
Array.join() ⭕ pure function
Array.reduce() ⭕ pure function
Array.slice() ⭕ pure function
Array.splice() ❌ impure function(return lefted parts of array)
Array.sort() ❌ impure function
Array.reverse() ❌ impure function
如果對 functional programming 有興趣(?),可以點參考資料內的連結了解更多
那麼,明天再來說明 pure function 與 react hook 之間的關係~
what are pure function & side effects
https://blog.greenroots.info/what-are-pure-functions-and-side-effects-in-javascript
https://enlear.academy/pure-vs-impure-function-395df7ce6acc
https://www.geeksforgeeks.org/pure-functions-in-javascript/
https://medium.com/geekculture/pure-vs-impure-functions-3f8693edf69b
more about functional programming
https://frontendmasters.com/courses/hardcore-js-v2/
https://yucj.gitbooks.io/mostly-adequate-guide-traditional-chinese/content/ch3.html